import 'dart:convert';

import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_switch/flutter_switch.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/utils/string_utils.dart';

import '../http/api.dart';
import '../routers/routers.dart';
import '../views/dialog_manager.dart';
import 'package:crypto/crypto.dart';

///
/// 实体店付款
///
class StorePay extends StatefulWidget {
  const StorePay({Key? key}) : super(key: key);

  @override
  State<StorePay> createState() => _StorePayState();
}

class _StorePayState extends State<StorePay> {
  var _num = '';
  var payPwd = '';

  confirm(BuildContext context) async {
    FocusManager.instance.primaryFocus?.unfocus();
    if (_num.isEmpty) {
      EasyLoading.showToast("请输入付款金额");
      return;
    }

    if (!StringUtils.isFloatNum(_num)) {
      EasyLoading.showToast("请输入正确的金额");
      return;
    }

    String isCheck = await checkPayPwd();
    if (isCheck == '1') {
      _showDialogForPinInput(context);
    } else {
      //请用户去设置支付密码
      DialogManager.showDefaultDialog(context, "你还未设置支付密码，请前往设置", () async {
        Routes.navigateTo(context, Routes.mineChangePassword, params: {'pageTitle': '修改支付密码'});
      });
    }
  }

  _showDialogForPinInput(context) {
    payPwd = '';
    AwesomeDialog(
      context: context,
      animType: AnimType.SCALE,
      dialogType: DialogType.NO_HEADER,
      body: Container(
        padding: EdgeInsets.only(top: 5.w, left: 20.w, right: 20.w),
        child: Column(
          children: [
            Text(
              "请输入支付密码",
              style: TextStyle(color: Config.colorText1, fontSize: 30.sp),
            ),
            Padding(
              padding: EdgeInsets.only(top: 30.w),
            ),
            PinCodeTextField(
              appContext: context,
              length: 6,
              obscureText: true,
              // controller: textEditingController,
              onChanged: (value) {},
              keyboardType: TextInputType.phone,
              onCompleted: (value) {
                payPwd = value;
              },
              // pinTheme: PinTheme(
              //   shape: PinCodeFieldShape.box, //输入框的形状
              //   borderRadius: const BorderRadius.all(Radius.circular(10)),
              //   // 其他可以设置可以自己参考，比如有输入文字的时候输入框是什么颜色，不能输入的时候是什么颜色等
              // ),
            ),
            InkWell(
              onTap: () {
                Routes.navigateTo(context, Routes.mineChangePassword,
                    params: {'pageTitle': '修改支付密码'});
              },
              child: Container(
                alignment: Alignment.centerRight,
                padding: EdgeInsets.only(right: 2.w),
                child: Text(
                  "忘记密码?",
                  style: TextStyle(
                      color: Config.colorText1,
                      fontSize: 25.sp,
                      decoration: TextDecoration.underline),
                ),
              ),
            ),
          ],
        ),
      ),
      title: '',
      desc: '',
      btnOkText: '确定',
      btnOkColor: Config.colorMain,
      btnOkOnPress: () {
        // print('oncompletd $payPwd');
        if (payPwd.isEmpty) {
          return;
        }
        transfer();
      },
    ).show();
  }

  checkPayPwd() async {
    dynamic result = await Api.checkSetPayPwd();
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      String pay_pwd_exists = jsonResult['data']['pay_pwd_exists'];
      return pay_pwd_exists;
    }
    return "0";
  }

  transfer() async {
    var content = const Utf8Encoder().convert(payPwd);
    String md5pwd = "${md5.convert(content)}";

    dynamic result = await Api.transfer({'money': _num, 'password': md5pwd});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      EasyLoading.showToast("支付成功");
      Routes.router.pop(context, {'result': 1});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Config.colorBg2,
      appBar: AppBar(
        title: const Text('消费付款'),
        centerTitle: true,
      ),
      body: SizedBox(
        width: double.infinity,
        height: double.infinity,
        child: Container(
          width: double.infinity,
          height: double.infinity,
          margin: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
          child: Column(
            children: [
              Container(
                width: double.infinity,
                height: 140.w,
                padding: EdgeInsets.symmetric(vertical: 25.w, horizontal: 25.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12.w),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "付款给商家",
                      style: TextStyle(fontSize: 24.sp, color: Config.colorText1),
                    ),
                    Padding(
                      padding: EdgeInsets.only(top: 8.w),
                    ),
                    Text(
                      '宝安47区xxx店铺',
                      style: TextStyle(
                          fontSize: 28.sp, color: Config.colorMain, fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
              ),
              Container(
                width: double.infinity,
                padding: EdgeInsets.symmetric(vertical: 20.w, horizontal: 20.w),
                margin: EdgeInsets.only(top: 25.w),
                decoration: BoxDecoration(
                  color: (Config.colorWhite),
                  borderRadius: BorderRadius.circular(10.w),
                ),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Text(
                          "付款金额",
                          style: TextStyle(fontSize: 24.sp, color: Config.colorText1),
                        ),
                      ],
                    ),
                    Divider(
                      color: Config.colorDivider,
                      height: 40.w,
                      thickness: 2.w,
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 5.w),
                          width: 100.w,
                          child: Text(
                            "金券",
                            style: TextStyle(fontSize: 25.sp),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 30.w),
                        ),
                        Container(
                          width: 500.w,
                          margin: EdgeInsets.symmetric(vertical: 5.w),
                          child: TextField(
                            keyboardType: TextInputType.number,
                            textAlign: TextAlign.justify,
                            obscureText: false,
                            maxLength: 10,
                            maxLines: 1,
                            onChanged: (value) {
                              setState(() {
                                _num = value;
                              });
                            },
                            inputFormatters: [
                              FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                            ],
                            style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                            decoration: const InputDecoration(
                              hintStyle: TextStyle(color: Config.colorText3),
                              hintText: "请输入付款金额",
                              counterText: '',
                              isDense: true,
                              border: InputBorder.none,
                              contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                            ),
                          ),
                        ),
                      ],
                    ),
                    // Divider(
                    //   color: Config.colorDivider,
                    //   height: 40.w,
                    //   thickness: 2.w,
                    // ),
                    // Row(
                    //   crossAxisAlignment: CrossAxisAlignment.center,
                    //   children: [
                    //     Container(
                    //       margin: EdgeInsets.symmetric(vertical: 5.w),
                    //       width: 100.w,
                    //       child: Text(
                    //         "支付密码",
                    //         style: TextStyle(fontSize: 25.sp),
                    //       ),
                    //     ),
                    //     Padding(
                    //       padding: EdgeInsets.only(left: 30.w),
                    //     ),
                    //     Row(
                    //       children: [
                    //         Container(
                    //           width: 310.w,
                    //           margin: EdgeInsets.symmetric(vertical: 5.w),
                    //           child: TextField(
                    //             keyboardType: TextInputType.number,
                    //             textAlign: TextAlign.justify,
                    //             obscureText: false,
                    //             maxLength: 6,
                    //             maxLines: 1,
                    //             onChanged: (value) {
                    //               setState(() {
                    //                 payPwd = value;
                    //               });
                    //             },
                    //             style: TextStyle(fontSize: 25.sp, color: Config.colorText1),
                    //             decoration: const InputDecoration(
                    //               hintStyle: TextStyle(color: Config.colorText3),
                    //               hintText: "请输入支付密码",
                    //               counterText: '',
                    //               isDense: true,
                    //               border: InputBorder.none,
                    //               contentPadding: EdgeInsets.zero, //设置文本内容的Padding
                    //             ),
                    //           ),
                    //         ),
                    //       ],
                    //     ),
                    //   ],
                    // ),
                  ],
                ),
              ),
              Container(
                width: 750.w,
                height: 100.w,
                padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 8.w),
                margin: EdgeInsets.only(top: 45.w),
                child: ElevatedButton(
                  clipBehavior: Clip.antiAlias,
                  onPressed: () => {confirm(context)},
                  style: ElevatedButton.styleFrom(shape: const StadiumBorder()),
                  child: const Text('付款'),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
